﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Medecine.Interface.Main;
using Medecine.DataAccess.Patients;
using GalaSoft.MvvmLight.Command;
using Medecine.Interface.Properties;
using GalaSoft.MvvmLight.Messaging;
using Medecine.Dbo;
using System.Reactive.Linq;

namespace Medecine.Interface.Patients
{
	public class AddPatientViewModel : ViewModelWithErrors
	{
		public AddPatientViewModel()
		{
			_patient = new Patient();
			_patient.Birthday = DateTime.Now;
			_addCommand = new RelayCommand(Add);
			_cancelCommand = new RelayCommand(Cancel);
		}

		#region Patient

		private readonly Patient _patient;
		public Patient Patient
		{
			get { return _patient; }
		}

		public string FirstName
		{
			get { return _patient.Firstname; }
			set
			{
				if (_patient.Firstname == value)
					return;
				_patient.Firstname = value;
				RaisePropertyChanged("FirstName");
			}
		}

		public string LastName
		{
			get { return _patient.Name; }
			set
			{
				if (_patient.Name == value)
					return;
				_patient.Name = value;
				RaisePropertyChanged("LastName");
			}
		}

		public DateTime Birthday
		{
			get { return _patient.Birthday; }
			set
			{
				if (_patient.Birthday == value)
					return;
				_patient.Birthday = value;
				RaisePropertyChanged("Birthday");
			}
		}

		#endregion // Patient

		#region Add

		private readonly RelayCommand _addCommand;
		public RelayCommand AddCommand { get { return _addCommand; } }

		private void Add()
		{
			using (ServicePatientClient service = new ServicePatientClient())
			{
				Observable.FromAsyncPattern<Patient, bool>(service.BeginAddPatient, service.EndAddPatient)
					.Invoke(Patient)
					.ObserveOnDispatcher()
					.Subscribe(AddCompleted, (e) => Messenger.Default.Send(new ErrorMessage(e.Message)));
			}
		}

		private void AddCompleted(bool result)
		{
			if (result == false)
				Messenger.Default.Send(new ErrorMessage(Resources.AddPatientError));
			else
			{
				Cancelled = false;
				Messenger.Default.Send(new GoToViewMessage(ViewName.Home));
			}
		}

		#endregion // Add

		#region Cancel

		private bool _cancelled = true;
		public bool Cancelled
		{
			get { return _cancelled; }
			private set { _cancelled = value; }
		}

		private readonly RelayCommand _cancelCommand;
		public RelayCommand CancelCommand { get { return _cancelCommand; } }

		private void Cancel()
		{
			Messenger.Default.Send(new GoToViewMessage(ViewName.Home));
		}

		#endregion // Cancel
	}
}
